package com.service;

import com.mapper.ProductMapper;
import com.mapper.ProductOrderMapper;
import com.mapper.SalesOrderDetailMapper;
import com.mapper.SalesOrderMapper;
import com.pojo.Product;
import com.pojo.ProductOrder;
import com.pojo.SalesOrder;
import com.pojo.SalesOrderDetail;
import com.pojo.requestjson.AddSalesProductDetailRequestJson;
import com.pojo.view.ShopCartView;
import com.service.iter.IProductsService;
import com.service.iter.ISaleOrderService;
import com.service.iter.IZfbService;
import com.util.OrderGenerator;
import com.util.Res;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;


/**
 * 销售订单服务业务层
 *
 * @author admin
 * @date 2023/06/20
 */
@Service
@Transactional
public class SaleOrderServiceImpl implements ISaleOrderService {
    /**
     * 销售订单映射器
     */
    private final SalesOrderMapper salesOrderMapper;
    /**
     * 销售订单详情映射器
     */
    private final SalesOrderDetailMapper salesOrderDetailMapper;
    /**
     * 产品订单映射器
     */
    private final ProductOrderMapper productOrderMapper;
    private final ProductMapper productMapper;
    private final IZfbService zfbService;
    private final IProductsService shopCartService;

    @Autowired
    public SaleOrderServiceImpl(SalesOrderMapper salesOrderMapper, SalesOrderDetailMapper salesOrderDetailMapper, ProductOrderMapper productOrderMapper, ProductMapper productMapper, IZfbService zfbService, IProductsService shopCartService) {
        this.salesOrderMapper = salesOrderMapper;
        this.salesOrderDetailMapper = salesOrderDetailMapper;
        this.productOrderMapper = productOrderMapper;
        this.productMapper = productMapper;
        this.zfbService = zfbService;
        this.shopCartService = shopCartService;
    }

    @Override
    public BigDecimal calculateTotalPrice(List<ShopCartView> shopCartList) {
        return shopCartList.stream()
                .map(cart -> cart.getPrice().multiply(BigDecimal.valueOf(cart.getProductQuantity())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    private SalesOrder createSalesOrder(AddSalesProductDetailRequestJson requestJson, List<ShopCartView> shopCartList) {
        SalesOrder salesOrder = new SalesOrder();
        LocalDateTime currentDate = LocalDateTime.now();
        LocalDateTime endDate = currentDate.plusDays(7);
        String salesOrderNo = OrderGenerator.generateOrderNumber("Sales");
        salesOrder.setEstimatedDeliveryTime(endDate);
        salesOrder.setSalesOrderNo(salesOrderNo);
        salesOrder.setSalesOrderTime(currentDate);
        salesOrder.setSalesOrderStatus(1L);
        salesOrder.setCustomName(requestJson.getCustomName());
        salesOrder.setCustomPhone(requestJson.getCustomPhone());
        salesOrder.setCustomAddrs(requestJson.getCustomAddress());
        BigDecimal totalPrice = calculateTotalPrice(shopCartList);
        salesOrder.setTotalPrice(totalPrice);
        return salesOrder;
    }

    private SalesOrderDetail createSalesOrderDetail(SalesOrder salesOrder, ShopCartView shopCart) {
        SalesOrderDetail salesOrderDetail = new SalesOrderDetail();
        String salesOrderNo = salesOrder.getSalesOrderNo();
        salesOrderDetail.setSalesOrderId(salesOrder.getSalesOrderId());
        salesOrderDetail.setSalesOrderNo(salesOrderNo);
        salesOrderDetail.setProductId(shopCart.getProductId());
        salesOrderDetail.setProductName(shopCart.getProductName());
        salesOrderDetail.setSalesDate(LocalDateTime.now());
        salesOrderDetail.setProductPrice(shopCart.getPrice());
        salesOrderDetail.setTotalPrice(salesOrder.getTotalPrice());
        salesOrderDetail.setState(1);
        salesOrderDetail.setProductQuantity(shopCart.getProductQuantity());
        salesOrderDetail.setSizeId(shopCart.getSizeId());
        return salesOrderDetail;
    }

    /**
     * 添加销售订单异步
     *
     * @param salesOrder 销售订单
     * @return {@link CompletableFuture}<{@link Boolean}>
     */private CompletableFuture<Boolean> addSalesOrderAsync(SalesOrder salesOrder) {
        return CompletableFuture.supplyAsync(() -> salesOrderMapper.addSalesOrder(salesOrder) == 1);
    }

    /**
     * 异步添加销售订单详细信息
     *
     * @param salesOrder  销售订单
     * @param productList 产品列表
     * @return {@link CompletableFuture}<{@link Boolean}>
     */
    private CompletableFuture<Boolean> addSalesOrderDetailsAsync(SalesOrder salesOrder, List<ShopCartView> productList) {
        return CompletableFuture.supplyAsync(() -> addSalesOrderDetails(salesOrder, productList));
    }

    /**
     * 支付订单异步
     *
     * @param orderNo 订单编号
     * @param totalPrice 总价
     * @return {@link CompletableFuture}<{@link Res}>
     */private CompletableFuture<Res> payOrderAsync(String orderNo, BigDecimal totalPrice) {
        return CompletableFuture.supplyAsync(() -> zfbService.payOrder(orderNo, totalPrice));
    }

    /**
     * 添加销售订单详细信息
     *
     * @param salesOrder   销售订单
     * @param shopCartList 产品列表
     * @return boolean
     */
    private boolean addSalesOrderDetails(SalesOrder salesOrder, List<ShopCartView> shopCartList) {
        List<SalesOrderDetail> salesOrderDetails = new ArrayList<>();
        for (ShopCartView shopCart : shopCartList) {
            SalesOrderDetail salesOrderDetail = createSalesOrderDetail(salesOrder, shopCart);
            if (salesOrderDetail != null) {
                salesOrderDetails.add(salesOrderDetail);
            }
        }
        return salesOrderDetailMapper.addSalesOrderDetails(salesOrderDetails) == salesOrderDetails.size();
    }

    /**
     * 添加销售订单
     *
     * @return {@link HashMap}<{@link String}, {@link Object}>
     */
    @Override
    public Res addSaleOrder(AddSalesProductDetailRequestJson requestJson) {
        Res res = new Res();
        try {
            List<ShopCartView> shopCartList = shopCartService.byConsumerPhoneGetShops(requestJson.getCustomPhone());
            if (shopCartList.isEmpty()) {
                res.setCode(405);
                res.setMsg("购物车为空");
                return res;
            }
            SalesOrder salesOrder = createSalesOrder(requestJson, shopCartList);
            CompletableFuture<Boolean> addOrderFuture = addSalesOrderAsync(salesOrder);
            CompletableFuture<Boolean> addDetailsFuture = addOrderFuture.thenComposeAsync(result -> addSalesOrderDetailsAsync(salesOrder, shopCartList));
            CompletableFuture.allOf(addOrderFuture, addDetailsFuture).join();
            if (!addOrderFuture.join()) {
                res.setCode(403);
                res.setMsg("销售订单录入失败");
                return res;
            }
            if (!addDetailsFuture.join()) {
                res.setCode(404);
                res.setMsg("销售订单详情录入失败");
                return res;
            }
            BigDecimal totalPrice = salesOrder.getTotalPrice();
            CompletableFuture<Res> paymentFuture = payOrderAsync(salesOrder.getSalesOrderNo(), totalPrice);
            Res paymentResponse = paymentFuture.join();
            Map<String, Object> map = new HashMap<>();
            if (paymentResponse.getCode() != 200) {
                res.setCode(paymentResponse.getCode());
                res.setMsg(paymentResponse.getMsg());
                return res;
            }
            map.put("code", paymentResponse.getData());
            map.put("OrderId", salesOrder.getSalesOrderId());
            res.setData(map);
            res.setCode(paymentResponse.getCode());
            res.setMsg(paymentResponse.getMsg());
            return res;
        } catch (Exception e) {
            res.setCode(500);
            res.setMsg("服务器内部错误: " + e.getMessage());
            return res;
        }
    }

    @Override
    public Res updateStatus(Long salesOrderId) {
        Res res = new Res();
        try {
            SalesOrder salesOrder = salesOrderMapper.QuerySalesOrder(salesOrderId);
            if (salesOrder == null) {
                res.setCode(404);
                res.setMsg("未找到对应的销售订单");
                return res;
            }
            String salesOrderNo = salesOrder.getSalesOrderNo();
            res = zfbService.queryOrder(salesOrderNo);
            if (res.getCode() != 200) {
                return res;
            }
            Long salesOrderStatus = salesOrder.getSalesOrderStatus();
            if (salesOrderStatus != null && salesOrderStatus == 1L) {
                if (salesOrderMapper.updateStatesById(2L, salesOrderId) < 1 ||
                        salesOrderDetailMapper.updateStatesById(2L, salesOrderId) < 1) {
                    res.setCode(202);
                    res.setMsg("更改订单状态失败，请联系管理员");
                    return res;
                }
            }
            salesOrder.setPaymentTime(LocalDateTime.now());
            salesOrder.setPaymentMethod(1L);
            Res emptyCartRes = shopCartService.emptyShopCart(salesOrder.getCustomPhone());
            if (emptyCartRes.getCode() != 200) {
                res.setCode(emptyCartRes.getCode());
                res.setMsg(emptyCartRes.getMsg());
                return res;
            }
        } catch (Exception e) {
            e.printStackTrace();
            res.setCode(500);
            res.setMsg("系统异常");
        }
        return res;
    }

    @Override
    public List<SalesOrder> QueryByCustomPhone(String customPhone) {
        List<SalesOrder> salesOrders = salesOrderMapper.QueryByCustomPhone(customPhone);
        System.out.println(salesOrders);
        return salesOrders;
    }

    private ProductOrder createProductOrder(String productOrderNumber, SalesOrderDetail salesOrderDetail, Product product, String salesOrderNo, String customName, String customAddrs, String customPhone) {
        ProductOrder productOrder = new ProductOrder();
        productOrder.setProductOrderCode(productOrderNumber);
        productOrder.setProductId(salesOrderDetail.getProductId());
        productOrder.setProductName(salesOrderDetail.getProductName());
        productOrder.setProductNumber(salesOrderDetail.getProductQuantity());
        productOrder.setCustomName(customName);
        productOrder.setCustomAddress(customAddrs);
        productOrder.setCustomPhone(customPhone);
        productOrder.setProductOrderStatus(1L);
        productOrder.setSizeId(Long.valueOf(salesOrderDetail.getSizeId()));
        productOrder.setCategoryId(product.getProductCategoryId());
        productOrder.setProductMaterial(product.getProductMaterial());
        productOrder.setProductOrderTime(new Date());
        productOrder.setSalesOrderNo(salesOrderNo);
        return productOrder;
    }

    private boolean addProductOrder(ProductOrder productOrder) {
        return productOrderMapper.addProductOrder(productOrder) > 0;
    }

    /**
     * 添加产品订单并修改订单状态
     *
     * @return {@link HashMap}<{@link String}, {@link Object}>
     */
    @Override
    public Res addProductOrder(Long salesOrderId) {
        Res res = new Res();
        try {
            SalesOrder salesOrder = salesOrderMapper.QuerySalesOrder(salesOrderId);
            String salesOrderNo = salesOrder.getSalesOrderNo();
            List<SalesOrderDetail> salesOrderDetails = salesOrderDetailMapper.QuerySalesOrderDetail(salesOrderId);
            if (salesOrderDetails.isEmpty()) {
                res.setCode(404);
                res.setMsg("空订单");
                return res;
            }
            String customAddrs = salesOrder.getCustomAddrs();
            String customName = salesOrder.getCustomName();
            String customPhone = salesOrder.getCustomPhone();
            Long salesOrderStatus = salesOrder.getSalesOrderStatus();
            for (SalesOrderDetail salesOrderDetail : salesOrderDetails) {
                String productOrderNumber = OrderGenerator.generateOrderNumber("Product");
                Long productId = salesOrderDetail.getProductId();
                Integer sizeId = salesOrderDetail.getSizeId();
                Product product = productMapper.getProductPrice(productId, sizeId);
                if (product == null) {
                    res.setCode(406);
                    res.setMsg("录入失败，没有该产品");
                    return res;
                }
                ProductOrder productOrder = createProductOrder(productOrderNumber, salesOrderDetail, product, salesOrderNo, customName, customAddrs, customPhone);
                if (!addProductOrder(productOrder)) {
                    res.setCode(405);
                    res.setMsg("产品订单详情录入失败");
                    return res;
                }
            }
            if (salesOrderStatus != null && (salesOrderStatus == 2L || salesOrderStatus == 10L)) {
                if (salesOrderStatus == 2L) {
                    salesOrderMapper.updateStatesById(10L, salesOrderId);
                }
                res.setCode(200);
                res.setMsg("产品订单生成成功");
            } else {
                res.setCode(300);
                res.setMsg("此订单不可再次生成产品订单");
            }
        } catch (Exception e) {
            e.printStackTrace();
            res.setCode(500);
            res.setMsg("系统异常");
        }
        return res;
    }
}
